/**
 * Copyright (C) 2008 aileron.cc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.aileron.mailet.daemon;

import static javax.mail.Flags.Flag.DELETED;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

import cc.aileron.mailet.Mailet;

import com.google.inject.Inject;


/**
 * mailet-daemon
 * @author Aileron
 *
 */
public class MailetDaemonListener
{
    /**
     * INBOX
     */
    private static String FOLDER_NAME = "INBOX";
    
    /**
     * constractor injection
     * @param setting
     * @throws MessagingException
     */
    @Inject
    public MailetDaemonListener(
            final MailetDaemonSetting setting,
            final MailetDaemonLogging logging,
            final Mailet mailet) throws MessagingException
    {
        final Session session = Session.getDefaultInstance(MailetDaemonSetting.properties, null);
        final Store store = session.getStore(setting.urlName());
        store.connect();
        this.folder = store.getFolder(FOLDER_NAME);
        this.mailet = mailet;
        this.logging = logging;
    }
    
    /**
     * logging
     */
    private final MailetDaemonLogging logging;
    
    /**
     * mailet
     */
    private final Mailet mailet;
    
    /**
     * store
     */
    private final Folder folder;
    
    /**
     * wait
     * @throws MessagingException 
     */
    public void listen() throws MessagingException
    {
        folder.open(Folder.READ_WRITE);
        if(folder.getUnreadMessageCount()>0)
        {
            for(final Message message : folder.getMessages())
            {
                try
                {
                    mailet.execute(message);
                    message.setFlag(DELETED, true);
                }
                catch(Exception e)
                {
                    logging.message(e);
                }
            }
        }
        folder.close(false);
    }
}